import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-16
 * Time: 8:29
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String severIp;
    private int severPort;
    public UdpEchoClient(String ip, int port) throws SocketException {
        socket = new DatagramSocket(); //客户端避免使用固定端口， 因为可能会导致端口竞争， 操作系统随机分配端口，
        this.severIp = ip;
        this.severPort = port;
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true){
            //1.从控制台读取用户输入的数据
            System.out.println("请输入要发送的内容:");
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.nextLine();
            //2.构造请求数据包， 把数据包发给服务器
            DatagramPacket datagramPacket = new DatagramPacket(request.getBytes()
                    , request.getBytes().length
                    , InetAddress.getByName(severIp), severPort); //包含服务器IP和端口
            //3.发送数据包
            socket.send(datagramPacket);
            //4.接受服务器的处理结果
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //5.从服务器接受的数据包中构造字符串， 打印结果
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }

    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
